package com.c611.smartclassroom.service.Impl;

import com.c611.smartclassroom.dto.AllClassRoomDto;
import com.c611.smartclassroom.dto.BuildClassDto;
import com.c611.smartclassroom.dto.ClassRoomDto;
import com.c611.smartclassroom.mapper.*;
import com.c611.smartclassroom.model.*;
import com.c611.smartclassroom.service.SchoolService;
import org.apache.ibatis.session.RowBounds;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional                  //添加事务注解
public class SchoolServiceImpl implements SchoolService {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    SchoolMapper schoolMapper;
    @Autowired
    BuildMapper buildMapper;
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    ClassRoomMapper classRoomMapper;
    @Autowired
    ZoneMapper zoneMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WorkOrderMapper workOrderMapper;
    @Autowired
    DeviceMapper deviceMapper;

    //缓存学校的总的数量
    @Cacheable(value = "school",key = "'querySchoolCount'")
    @Override
    public long querySchoolCount() {
        SchoolExample schoolExample = new SchoolExample();
        schoolExample.createCriteria().andDelflagNotEqualTo(1);

        return schoolMapper.countByExample(schoolExample);
    }

    //缓存学校id是否重复
    @Cacheable(value = "school",key = "'checkSchoolId::' + #schoolid")
    @Override
    public int checkSchoolId(String schoolid) {
        School school = schoolMapper.selectByPrimaryKey(schoolid);
        if(school == null) return 0;
        return 1;
    }

    //缓存学校的分页查询的结果
    @Cacheable(value = "school",key = "'queryAllSchool::' + #page + '::' + #pageSize",unless = "#result == null ")
    @Override
    public List<School> queryAllSchool(Integer page,Integer pageSize) {

        //增加分页
        RowBounds RowBounds = new RowBounds((page - 1) * pageSize,pageSize);
        SchoolExample schoolExample = new SchoolExample();


        //构造器，查询置费标识为1的记录
        //SchoolExample schoolExample = new SchoolExample();
        schoolExample.createCriteria().andDelflagNotEqualTo(1);
        //return schoolMapper.selectByExample(schoolExample,RowBounds);
        return schoolMapper.selectByExampleWithRowbounds(schoolExample,RowBounds);
    }

    //缓存学校根据学校名字分页查询学校
    @Cacheable(value = "school",key = "'queryAllSchoolByschoolName::' + #page + '::' + #pageSize + '::' + #schoolName",unless = "#result == null ")
    @Override
    public List<School> queryAllSchoolByschoolName(Integer page, Integer pageSize,String schoolName) {
        RowBounds rowBounds = new RowBounds((page - 1) * pageSize,pageSize);
        SchoolExample schoolExample = new SchoolExample();
        //schoolExample.setOrderByClause("queryAllSchoolByschoolName");
        schoolExample.createCriteria().andDelflagEqualTo(0).andSchoolnameLike("%" + schoolName +"%");
        return schoolMapper.selectByExampleWithRowbounds(schoolExample,rowBounds);
    }

    @Cacheable(value = "school",key = "'queryAllSchoolCountByschoolName::' + #schoolName")
    @Override
    public long queryAllSchoolCountByschoolName(String schoolName) {

        SchoolExample schoolExample = new SchoolExample();
        schoolExample.createCriteria().andDelflagEqualTo(0).andSchoolnameLike("%" + schoolName + "%");
        return schoolMapper.countByExample(schoolExample);
    }

    //清除学校区域的缓存
    @CacheEvict(value = {"school","school::build","school::build::class"},allEntries = true)
    @Override
    public int setWeChat(String schoolID, String weChat) {
//        SchoolExample schoolExample = new SchoolExample();
//        schoolExample.createCriteria().andSchoolidEqualTo(schoolID);
//        update t_school set wechat =  where schoolID = 1

        School school = new School();
        school.setSchoolid(schoolID);
        school.setWechat(weChat);
        //通过主键，对wechat字段进行更新
        return schoolMapper.updateByPrimaryKeySelective(school);
    }

    @CacheEvict(value = {"school","school::build","school::build::class"},allEntries = true)
    @Override
    public int addSchool(School school) {
        school.setAddtime(new Date());
        //return schoolMapper.insert(school);


        return schoolMapper.insertSelective(school);
    }

    @CacheEvict(value = {"school","school::build","school::build::class"},allEntries = true)
    @Override
    public int saveSchool(School school) {

        //修改教学楼学校ID
//        Build build = new Build();
//        build.setSchoolid(school.getSchoolid());
//        BuildExample buildExample = new BuildExample();
//        buildExample.createCriteria().andSchoolidEqualTo()
//        buildMapper.updateByExampleSelective()
        //修改用户所属学校名称
        User user = new User();
        user.setSchoolname(school.getSchoolname());
        UserExample userExample = new UserExample();
        userExample.createCriteria().andSchoolidEqualTo(school.getSchoolid());
        userMapper.updateByExampleSelective(user,userExample);


        return schoolMapper.updateByPrimaryKeySelective(school);

    }

    @CacheEvict(value = {"school","school::build","school::build::class"},allEntries = true)
    @Override
    public int delSchool(String schoolID) {

        //根据schoolID，进行删除（将置费标识置于1）
        School school = new School();
        school.setDelflag(1);
        school.setSchoolid(schoolID);

        //根据学校ID，删除区域表里与改学校相关的区域
        Zone zone = new Zone();
        zone.setDelflag(1);
        zone.setSchoolid(schoolID);
        ZoneExample zoneExample = new ZoneExample();
        zoneExample.createCriteria().andSchoolidEqualTo(schoolID);
        zoneMapper.updateByExampleSelective(zone,zoneExample);

        //删除与学校相关的所有教学楼
        Build build = new Build();
        build.setSchoolid(schoolID);
        build.setDelflag(1);
        BuildExample buildExample = new BuildExample();
        buildExample.createCriteria().andSchoolidEqualTo(schoolID);
        buildMapper.updateByExampleSelective(build,buildExample);

        //删除与学校相关的所有用户
        User user = new User();
        user.setSchoolid(schoolID);
        user.setDelflag(1);
        UserExample userExample = new UserExample();
        userExample.createCriteria().andSchoolidEqualTo(schoolID);
        userMapper.updateByExampleSelective(user,userExample);

        //删除与学校相关的所有工单
        WorkOrder workOrder = new WorkOrder();
        workOrder.setSchoolid(schoolID);
        workOrder.setDelflag(1);
        WorkOrderExample workOrderExample = new WorkOrderExample();
        workOrderExample.createCriteria().andSchoolidEqualTo(schoolID);
        workOrderMapper.updateByExampleSelective(workOrder,workOrderExample);

        //删除与学校相关的所有设备
        Device device = new Device();
        device.setSchoolid(schoolID);
        device.setDelflag(1);
        DeviceExample deviceExample = new DeviceExample();
        deviceExample.createCriteria().andSchoolidEqualTo(schoolID);
        deviceMapper.updateByExampleSelective(device,deviceExample);

        return schoolMapper.updateByPrimaryKeySelective(school);
    }

    /**
     * yw
     */
//    @Cacheable(value = "school",key = "'getAllSchoolName'",unless = "#result == null ")
    @Override
    public List<ObjectSelect> getAllSchoolName(){
        return schoolMapper.getAllSchoolName();
    }


    @Cacheable(value = "class",key = "'queryCalss::' + #buildID",unless = "#result == null ")
    @Override
    public List<ClassRoom> queryCalss(String buildID) {
        //根据buildID，查询该教学楼下的所有教室
        ClassRoomExample classRoomExample = new ClassRoomExample();
        classRoomExample.createCriteria().andTbuildidEqualTo(buildID).andDelflagNotEqualTo(1);
        return classRoomMapper.selectByExample(classRoomExample);
    }

    @Cacheable(value = "school::build",key = "'getAllSchoolBuildName'",unless = "#result == null ")
    @Override
    public List<SchoolBuildSelect> getAllSchoolBuildName(){
        List<SchoolBuildSelect> schoolBuildSelectsList = new ArrayList<SchoolBuildSelect>();
        //yw 得到所有学校名和学校id
        List<ObjectSelect> schoolList = schoolMapper.getAllSchoolName();
        //yw debug pass
//        ObjectSelect kk = new ObjectSelect("","");
//        SchoolBuildSelect schoolBuild1 = new SchoolBuildSelect();
//        schoolBuild1.setP("实验中学");
//        schoolBuild1.setPid(201);
//        schoolBuild1.setC(buildMapper.queryBuildNameBySchoolid("201"));
//        schoolBuildSelectsList.add(schoolBuild1);
        //yw debug
        List<String> buildNameList = new ArrayList<String>();
        List<String> buildIdList = new ArrayList<String>();
        for(ObjectSelect k:schoolList){

//            System.out.println(k);

            SchoolBuildSelect schoolBuild = new SchoolBuildSelect();
            schoolBuild.setP(k.getName());
            schoolBuild.setPid(k.getId());
            buildNameList = buildMapper.queryBuildNameBySchoolid(k.getId());
            if(buildNameList.size()>0){
                buildIdList = buildMapper.queryBuildIdBySchoolid(k.getId());
                schoolBuild.setC(buildNameList);
                schoolBuild.setCid(buildIdList);
                schoolBuildSelectsList.add(schoolBuild);
            }
        }
        return schoolBuildSelectsList;
    }

    @Cacheable(value = "build",key = "'getAlltBuildNameIDByschoolId::' + #schoolID",unless = "#result == null ")
    @Override
    public List<ObjectSelect> getAlltBuildNameIDByschoolId(String schoolID){
        return buildMapper.queryBuildNameIDBySchoolid(schoolID);
    }

//    @Cacheable(value = "class",key = "'getAllSchoolBuildRoom'",unless = "#result == null ")
    @Override
    public List<AllClassRoomDto> getAllSchoolBuildRoom() {
        //获得学校和所有的教学楼
        List<SchoolBuildSelect> init = getAllSchoolBuildName();
        //学校的集合
        List<AllClassRoomDto> list1 = new ArrayList<>();

        for (SchoolBuildSelect schoolBuildSelect : init) {
            //学校对象
            AllClassRoomDto allClassRoomDto = new AllClassRoomDto(schoolBuildSelect.getP(),schoolBuildSelect.getPid());
            //教学楼的集合
            List<BuildClassDto> list2 = new ArrayList<>();
            for (int i = 0;i < schoolBuildSelect.getC().size();i++) {
                //教学楼对象
                BuildClassDto buildClassDto = new BuildClassDto(schoolBuildSelect.getC().get(i),schoolBuildSelect.getCid().get(i));
                //根据教学楼对象的楼id去查该楼的所有教室
                ClassRoomExample classRoomExample = new ClassRoomExample();
                classRoomExample.createCriteria()
                        .andTbuildidEqualTo(buildClassDto.getCid())
                        .andDelflagEqualTo(0);
                List<ClassRoom> classRoom = classRoomMapper.selectByExample(classRoomExample);
                //遍历查询出来的集合，封装成为新的Map集合
                List<ClassRoomDto> list3 = new ArrayList<>();
                for (ClassRoom room : classRoom) {
                    list3.add(new ClassRoomDto(room.getClassroom(),room.getClassroomid()));
                }
                buildClassDto.setRoom(list3);
                list2.add(buildClassDto);
            }
            allClassRoomDto.setBuild(list2);
            list1.add(allClassRoomDto);
        }
        return list1;
    }
}
